/**
* @Title: BasicInterceptor.java
* @Package com.yly.common.basic.interceptors
* @Description: TODO
* @author zz
* @date 2013-12-16 上午10:27:27
* @version V1.0
*/
package com.yly.common.basic.interceptors.struts;

import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.yly.utils.StrUtil;
import com.yly.utils.ThreadLocalUtil;

/**
 * @ClassName: BasicInterceptor
 * @Description: TODO
 * @author zz
 * @date 2013-12-16 上午10:27:27
 */
public abstract class BasicInterceptor extends AbstractInterceptor {

	/* (非 Javadoc)
	 * <p>Title: intercept</p>
	 * <p>Description: </p>
	 * @param invocation
	 * @return
	 * @throws Exception
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		String result = null;
		if(ThreadLocalUtil.get("_INVOCATION._ACTION_INVOCATION") == null){
			ThreadLocalUtil.set("_INVOCATION._ACTION_INVOCATION", actionInvocation);
		}
		try{
			result = this.beforeExecute();
			if(StrUtil.nil(result)){
				result = actionInvocation.invoke();
				String afterResult = this.afterExecute();
				if(StrUtil.nil(afterResult)){
					result = afterResult;
				}
			}
		}catch(Throwable ex){
			ThreadLocalUtil.set("_INVOCATION._THROWABLE", actionInvocation);
			String exResult = this.exceptionExecute();
			if(StrUtil.nil(exResult)){
				result = exResult;
			}
			ex.printStackTrace();
		}finally{
			this.finallyExecute();
		}
		ThreadLocalUtil.remove("_INVOCATION._ACTION_INVOCATION");
		return result;
	}
	
	/**
	 * <p>Title:获得线程ActionInvocation对象 </p>
	 * <p>Description: 获得线程ActionInvocation对象</p>
	 * @return 线程ActionInvocation对象
	 */
	protected ActionInvocation getActionInvocation(){
		return (ActionInvocation)ThreadLocalUtil.get("_INVOCATION._ACTION_INVOCATION");
	}
	
	/**
	 * <p>Title:获得线程Throwable对象 </p>
	 * <p>Description: 获得线程Throwable对象</p>
	 * @return 线程Throwable对象
	 */
	protected Throwable getThrowable(){
		return (Throwable)ThreadLocalUtil.get("_INVOCATION._INVOCATION._THROWABLE");
	}
	
	/**
	 * <p>Title: 执行前需要完成的动作</p>
	 * <p>Description: 执行前需要完成的动作</p>
	 */
	protected abstract String beforeExecute();
	
	/**
	 * <p>Title: 执行后需要完成的动作</p>
	 * <p>Description: 执行后需要完成的动作</p>
	 */
	protected abstract String afterExecute();
	
	/**
	 * <p>Title: 执行过程中出现异常需要完成的动作</p>
	 * <p>Description: 执行过程中出现异常需要完成的动作(catch里的动作)</p>
	 * @return 需要返回的URL
	 */
	protected abstract String exceptionExecute();
	
	/**
	 * <p>Title: 执行完毕后需要完成的动作</p>
	 * <p>Description: 执行完毕后需要完成的动作(finally里的动作)</p>
	 */
	protected abstract void finallyExecute();
}
